package com.hw.elasticsearch.controller;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.elasticsearch.cluster.metadata.AliasMetaData;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hw.elasticsearch.model.User;

@Controller
public class ElasticController {

	@Autowired
	ElasticsearchTemplate est;
	
	@RequestMapping("createIndex")
	@ResponseBody
	public String createIndex() {
		est.createIndex("users", User.class);
		
		return est.queryForAlias("users").toString();
	}
	
	@RequestMapping("putUser")
	@ResponseBody
	public String putUser(Long id,String name,int age,String sex) {
		
		User user=new User(id,name,age,sex);
        IndexQuery indexQuery = new IndexQueryBuilder().withObject(user).build();
//        IndexQuery indexQuery = new IndexQueryBuilder().withId(user.getId()).withObject(User.class).build();
        est.index(indexQuery);

        List<AliasMetaData> userlist=est.queryForAlias("users");
        List<User> users=new ArrayList<>();
        
        for (AliasMetaData d : userlist) {
        	System.out.println(d);
//			users.add((User)d);
		}
		return userlist.toString();
	}
	
	@RequestMapping("allUser")
	@ResponseBody
	public String allUser() {
		SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchAllQuery()).build();
		return est.queryForList(searchQuery, User.class).toString();
	}
	
	@RequestMapping("getUser")
	@ResponseBody
	public String getUser(String name) {
		SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchQuery("name",name)).build();
		return est.queryForList(searchQuery, User.class).toString();
	}
}
